package com.study.tomcat.v3;

import javax.servlet.Servlet;
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.Map;

/**
 * 项目加载 部署
 *
 * @author: chenhs
 * @date: Created in 15:56 2019/12/21
 **/
public class ProjectUtil {

    public static Map<String, WebXml> load() throws Exception {

        Map<String, WebXml> projectInfos = new HashMap<>();

        //扫描对应的部署文件夹
        String webapps = "D:\\studio\\tomcat-tony\\webapps";

        File[] projects = new File(webapps).listFiles(pathname -> pathname.isDirectory());

        /**
         * 0. war部署之前，自动解压（java操作压缩包的API）【本质就是压缩包zip/rar】
         * 1. 文件夹形式
         */
        for (File project : projects) {
            //2. 发现项目里面所有的servlet --- web.xml或者注解（方式）
            WebXml webXml = new WebXmlConfigUtil().loadXml(project.getPath()+"\\WEB-INF\\web.xml");
            webXml.projectPath = project.getPath();
            webXml.loadServlet();

            projectInfos.put(project.getName(), webXml);
        }

        return projectInfos;
    }


    /**
     * xml文件对应的java对象
     */
    public class WebXml {
        public String projectPath = null;

        //name: class
        public Map<String, Object> servlets = new HashMap<>();

        //url: servletName
        public Map<String, String> servletMapping = new HashMap<>();

        //servletname: 实例对象
        public Map<String, Servlet> servletInstances = new HashMap<>();

        public void loadServlet() throws Exception {
            // JVM加载class
            //URL url = new URL("file:" + projectPath + "\\WEB-INF\\classes");
            //URLClassLoader classLoader = new URLClassLoader(new URL[]{url});
            MyClassLoader classLoader = new MyClassLoader(projectPath + "\\WEB-INF\\classes");

            for (Map.Entry<String, Object> entry : servlets.entrySet()) {
                //servlet名称
                String servletName = entry.getKey();
                //全类名
                String servletClassName = entry.getValue().toString();

                //加载
                Class<?> aClass = classLoader.loadClass(servletClassName);
                //反射 创建对象
                Servlet servlet = (Servlet) aClass.newInstance();
                servletInstances.put(servletName, servlet);
            }

        }
    }

}
